<?php
/**
 * 文章
 */
class ArticleModule
{
    public function comments() {
        global $_FANWE;

        $home_uid = intval($_GET['uid']);
        if(!$home_uid) exit('');

        $home_user = FS('User')->getUserById($home_uid);
        if(!$home_user['status']) {
            fHeader('location: /missing.html');
            exit;
        }

        $sql = 'SELECT * FROM '.FDB::table('wogu_order')." WHERE shopid={$home_uid} AND flag=2";
        $comment_list = FDB::fetchAll($sql);
        $grade0 = $grade1 = $grade2 = $gradeall = 0;
        foreach($comment_list as $v) {
            //if(empty($v['comment'])) $v['comment'] = '默认好评';
            $gradeall++;
            if($v['grade'] == 0) $grade0 ++;
            if($v['grade'] == 1) $grade1 ++;
            if($v['grade'] == 2) $grade2 ++;
        }

        $sql = 'SELECT * FROM '.FDB::table('wogu_user_shop').' WHERE uid='.$home_uid;
        $shopinfo = FDB::fetchFirst($sql);

        if(isset($_GET['type'])) {
            $type = intval($_GET['type']);
        }
        $_FANWE['nav_title'] = '评价列表';
        include template('page/article/article_comments');
        display();
        exit;
    }

    public function index()
    {
        global $_FANWE;

        $uid = intval($_GET['uid']);
        $cate_id = intval($_GET['cate']);
        $where = 'flag=0 AND status=1 AND jiage=0';
        if(!$uid) {
            $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE cate_id = '.$cate_id.' AND status <>0';
            $r = FDB::fetchFirst($sql);
            if(!$r){
                fHeader('location: '.FU('index'));
                exit;
            }
            /*
            if($_FANWE['user']['reside_province'] > 0 && !isset($_GET['cityid']) && !isset($_GET['provinceid'])) {
                $cities = include './public/city.php';
                $cityname = $cities['all'][$_FANWE['user']['reside_city']]['name'];
                fHeader("location: /article.php?action=index&cate={$cate_id}&cityid={$_FANWE['user']['reside_city']}&areaname={$cityname}&anli=".intval($_GET['anli']));
                exit;
            }*/

            $parent_id = $r['parent_id'] == 0 ? $cate_id : $r['parent_id'];
            $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE parent_id='.$parent_id . ' AND status!=0 ORDER BY sort ASC';
            $cates = FDB::fetchAll($sql);
            $cate_ids = array($cate_id);
            foreach($cates as $v) {
                $cate_ids[] = $v['cate_id'];
            }
            $where .= ' AND cate_id IN('.($r['parent_id'] == 0 ? implode(',', $cate_ids) : $cate_id).')';

    		//tags
    		$sql = 'SELECT tag_id FROM '.FDB::table('goods_category_tags').' WHERE cate_id='.$parent_id;
    		$gctags = FDB::fetchAll($sql);
    		$tagids = $tag_list = array();
    		foreach($gctags as $v) {
    		    $tagids[] = $v['tag_id'];
    		}
    		if(!empty($tagids)) {
        		$sql = 'SELECT * FROM '.FDB::table('goods_tags').' WHERE tag_id IN ('.implode(',', $tagids).')';
        		$tag_list = FDB::fetchAll($sql);
    		}
        } else {
            $where .= ' AND uid='.$uid;
        }
        //价格
        if(isset($_GET['minprice']) && $_GET['minprice'] !== '') {
            $minprice = intval($_GET['minprice']);
            $where .= ' AND price>='.$minprice;
        }
        if(isset($_GET['maxprice']) && $_GET['maxprice'] !== '') {
            $maxprice = intval($_GET['maxprice']);
            $where .= ' AND price<='.$maxprice;
        }

        $keywordsshow = array();
        $keywords = empty($r['search_keywords']) ? array() : explode(' ', $r['search_keywords']);
        $ids = empty($_GET['ids']) && $_GET['ids'] !== '0' ? array() : explode(',', $_GET['ids']);
        foreach($ids as $k => $id) {
            if(!is_numeric($id))
                unset($ids[$k]);
        }
        if(!empty($ids)) {
            $where .= ' AND (1';
            foreach($ids as $id) {
                if(isset($keywords[$id])) {
                    $where .= " AND title LIKE '%{$keywords[$id]}%'";
                    $keywordsshow[$id] = array('id' => $id, 'keyword' => $keywords[$id], 'checked' => true);
                }
            }
            $where .= ')';
        }
        foreach($keywords as $key => $v) {
            if(!isset($keywordsshow[$key])) {
                $keywordsshow[$key] = array('id' => $key, 'keyword' => $v, 'checked' => false);
            }
        }

        //地区
        if(!empty($_GET['cityid'])) {
            $cityidarr = explode(',', $_GET['cityid']);
            foreach($cityidarr as $k => $v) {
                if(!is_numeric($v)) {
                    unset($cityidarr[$k]);
                }
            }
            if(!empty($cityidarr)) {
                $cityidstr = implode(',', $cityidarr);
                $where .= ' AND city IN('.$cityidstr.')';
            }
        } elseif(!empty($_GET['provinceid']) && is_numeric($_GET['provinceid'])) {
            $provinceid = intval($_GET['provinceid']);
            $where .= ' AND province='.$provinceid;
        }
        if(!empty($_GET['areaname'])) {
            $areaname = htmlspecialchars($_GET['areaname']);
            $areanamearr = explode(',', $areaname);
        }

        // 经验/案例
        $anli = intval($_GET['anli']);
        if(isset($_GET['anli'])) {
            $where .= ' AND anli='.$anli;
        }

        // V商家
        if(isset($_GET['vshop'])) {
            $where .= ' AND uid!=0';
        }

		$orderkeys = array('sharenum', 'commentnum', 'priceup', 'pricedown', 'zannum');
		$orders = array('sharenum' => 'share_num DESC', 'commentnum' => 'comment_count DESC', 'default' => 'sort ASC,id DESC', 'priceup' => 'price ASC', 'pricedown' => 'price DESC', 'zannum' => 'zai_num DESC');
		$orderkey = in_array($_GET['order'], $orderkeys) ? $_GET['order'] : 'default';
		$order = $orders[$orderkey];

        $sql = 'SELECT COUNT(id) FROM '.FDB::table('article').' WHERE '.$where;
        $count = FDB::resultFirst($sql);
        $page_args = array();
        $pager = buildPage('article/'.ACTION_NAME,$page_args,$count,$_FANWE['page'],10);
        $article_list = array();
        if($_FANWE['page'] <= $pager['page']) {
            $pb_page_args = $page_args;
            $pb_page_args['page'] = $_FANWE['page'];
            $pb_page_args['pindex'] = '_pindex_';
            if($uid)
                $pb_page_args['uid'] = $uid;
            else
                $pb_page_args['cate'] = $cate_id;
            $pb_page_args['order'] = $orderkey;
            if(isset($_GET['minprice']) && $_GET['minprice'] !== '') {
                $pb_page_args['minprice'] = $minprice;
            }
            if(isset($_GET['maxprice']) && $_GET['maxprice'] !== '') {
                $pb_page_args['maxprice'] = $maxprice;
            }
            if(!empty($_GET['ids'])) {
                $pb_page_args['ids'] = implode(',', $ids);
            }
            if(!empty($cityidarr)) {
                $pb_page_args['cityid'] = implode(',', $cityidarr);
            }elseif(!empty($_GET['provinceid']) && is_numeric($_GET['provinceid'])) {
                $pb_page_args['provinceid'] = $_GET['provinceid'];
            }
            if(isset($_GET['anli'])) {
                $pb_page_args['anli'] = $anli;
            }
            $pb_url = $_FANWE['site_root'].'services/service.php?m=article&a=list&'.http_build_query($pb_page_args);
            if(isset($_GET['vshop'])) {
                $pb_url .= '&vshop';
            }
            $sql = 'SELECT * FROM '.FDB::table('article').' WHERE '.$where.' ORDER BY '.$order.' LIMIT '.$pager['limit'];
            $article_list = FDB::fetchAll($sql);
            if(!empty($article_list)){
                $cities = include './public/city.php';
                require FANWE_ROOT.'core/function/wogu.func.php';

                $uids = array();
                foreach ($article_list as $key => $value) {
                    if($value['uid']) {
                        $uids[] = $value['uid'];
                    }

                    if(isset($_GET['ajax'])) {
                        $article_list[$key]['img'] = create_mob_img($article_list[$key]['img']);
                    }
                    $article_list[$key]['province_show'] = $cities['all'][$value['province']]['name'];
                    $article_list[$key]['city_show'] = $cities['all'][$value['city']]['name'];

                    $sj = time();
                    $article_list[$key]['hascoupon'] = ($value['price2'] > 0 && ($value['bsj']==0 || $value['esj']==0 || ($sj >= $value['bsj'] && $sj < $value['esj']))) ? 1 : 0;
                }
                $uids = array_unique($uids);
                $sql = 'SELECT * FROM '.FDB::table('user').' WHERE uid IN ('.implode(',', $uids).')';
                $tmp = FDB::fetchAll($sql);
                $name_list = array();
                foreach ($tmp as $key => $value) {
                    $name_list[$value['uid']] = $value;
                }

                $sql = 'SELECT * FROM '.FDB::table('wogu_user_shop').' WHERE uid IN ('.implode(',', $uids).')';
                $tmp = FDB::fetchAll($sql);
                $shop_list = array();
                foreach ($tmp as $key => $value) {
                    $shop_list[$value['uid']] = $value;
                }
 
                foreach ($article_list as $key => $value) {
                    $article_list[$key]['author'] = $name_list[$value['uid']]['user_name'];
                    $article_list[$key]['shopinfo'] = $shop_list[$value['uid']];
                }
            }
        }

        if(isset($_GET['ajax'])) {
            echo json_encode(array(
                'list' => $article_list,
                'count' => $count
            ));
        } else {
            include template('page/article/article_index');
            display();
            exit;
        }
    }

    public function show()
    {
        global $_FANWE;

        $id = $_FANWE['request']['id'];
        if(!is_numeric($id)){
            fHeader('location: '.FU('article/index'));
            exit;
        }
        $share_detail = FS('Article')->getShareDetail($id);
        if($share_detail['flag'] == 1 || $share_detail['jb_num'] >= 100) {
            fHeader('location: /missing.html');
            exit;
        }

        $_FANWE['nav_title'] = $share_detail['title'];
        $_FANWE['seo_keywords'] = $share_detail['seo_keywords'];
        $_FANWE['seo_description'] = $share_detail['seo_desc'];

        if(!empty($share_detail['keyword'])) {
            $sql = 'SELECT * FROM '.FDB::table('article').' WHERE title LIKE \'%'.$share_detail['keyword'].'%\' ORDER BY comment_count DESC LIMIT 5';
            $article_list = FDB::fetchAll($sql);
        }
        $home_uid = $share_detail['uid'];
        $home_user = FS('User')->getUserById($home_uid);
        if(!$home_user['status']) {
            fHeader('location: /missing.html');
            exit;
        }

        if($share_detail['anli']) {
            //$sql = 'SELECT * FROM '.FDB::table('wogu_order')." WHERE artid={$share_detail['id']} AND flag=2 AND comment!=''";
            // modify by wogu@2017-05-21#显示该商家的全部评论
            $sql = 'SELECT * FROM '.FDB::table('wogu_order')." WHERE shopid={$share_detail['uid']} AND flag=4";
            $comment_list = FDB::fetchAll($sql);
            $grade0 = $grade1 = $grade2 = $gradeall = 0;
            foreach($comment_list as $v) {
                $gradeall++;
                if($v['grade'] == 0) $grade0 ++;
                if($v['grade'] == 1) $grade1 ++;
                if($v['grade'] == 2) $grade2 ++;
            }

            $sql = 'SELECT * FROM '.FDB::table('wogu_user_shop').' WHERE uid='.$share_detail['uid'];
            $shopinfo = FDB::fetchFirst($sql);

            $sql = 'SELECT * FROM '.FDB::table('wogu_realname_shop').' WHERE uid='.$share_detail['uid'];
            $realname = FDB::fetchFirst($sql);

            $sql = 'SELECT * FROM '.FDB::table('wogu_order').' WHERE artid='.$share_detail['id'].' AND isstop!=1 AND userid='.$_FANWE['uid'] . ' ORDER BY id DESC';
            $orderinfo = FDB::fetchFirst($sql);
            // 所有评论
            $sql = 'SELECT id,comment,comment2,add_time,add_time2,grade,img1,img2,img3,img4,img5,img6,img7,img8,img9,userid FROM '.FDB::table('wogu_order').' WHERE artid='.$share_detail['id']." AND flag=4 AND comment!='' ORDER BY id DESC";
            $comments_tmp = FDB::fetchAll($sql);
            $comments = array();
            if(!empty($comments_tmp)) {
                foreach ($comments_tmp as $val) {
                    $uids[] = $val['userid'];
                }

                $uids = array_unique($uids);
                $users_tmp = FDB::fetchAll("SELECT avatar,uid,user_name FROM ".FDB::table('user')." WHERE uid IN(".implode(',', $uids).")");
                $users = array();
                foreach ($users_tmp as $v) {
                    $users[$v['uid']] = $v;
                }

                foreach ($comments_tmp as $val) {
                    $comment = array(
                        'id' => $val['id'],
                        'avatar' => avatar($users[$val['userid']]['avatar']),
                        'user_name' => $users[$val['userid']]['user_name'],
                        'comment' => $val['comment'],
                        'add_time' => date('y/m/d', strtotime($val['add_time'])),
                        'add_time2' => date('y/m/d', strtotime($val['add_time2'])),
                        'comment2' => $val['comment2'],
                        'grade' => $val['grade'],
                        'imgs' => array(),

                    );
                    for($i = 1; $i <= 9; $i++) {
                        if(!empty($val['img'.$i])) {
                            $comment['imgs'][] = trim($val['img'.$i], './');
                        }
                    }
                    $comments[] = $comment;
                }
            }
        } else {
            //评论
    		$share_detail['comments'] = FS('Article')->getShareCommentList($id,'0,10');
    		//分享评论分页
    		$pager = buildPage('',array(),$share_detail['comment_count'],$_FANWE['page'],10);
        }

        $currcate = $_FANWE['cache']['goods_category']['all'][$share_detail['cate_id']];
        $parentcate = $_FANWE['cache']['goods_category']['all'][$currcate['parent_id']];
        $paytype = intval($_GET['paytype']);
        $orderid = intval($_GET['orderid']);

        if(isset($_GET['ajax'])) {
            require FANWE_ROOT.'core/function/wogu.func.php';
            $share_detail['img'] = create_mob_img($share_detail['img']);
            $share_detail['author'] = empty($share_detail['uid']) ? '火锅阁' : $home_user['user_name'];
            $share_detail['create_time'] = date('Y-m-d', $share_detail['create_time']);
            $share_detail['content'] = str_replace('src="/ueditor/', 'src="'.$_FANWE['site_url'].'ueditor/', $share_detail['content']);
            $share_detail['content'] = str_replace('src="/public/', 'src="'.$_FANWE['site_url'].'public/', $share_detail['content']);
            $share_detail['telphone'] = $shopinfo['telphone'];
            $share_detail['lat'] = $realname['lat'];
            $share_detail['lng'] = $realname['lng'];
            $share_detail['realname_status'] = $realname['flag'];
            $share_detail['comments'] = $comments;
            //print_r($share_detail);exit;
            exit(json_encode($share_detail));
        } else {
            include template('page/article/article_show');
            display();
            exit;
        }
    }

    public function jb() {
        global $_FANWE;

        $id = intval($_GET['id']);
        if($id) {
            $sql = 'UPDATE '.FDB::table('article').' SET jb_num=jb_num+1 WHERE id='.$id;
            FDB::query($sql);
        }
        echo '举报成功';
    }

    public function doinit() {
        global $_FANWE;

        $paytype = intval($_GET['paytype']);
        $artid = intval($_GET['artid']);

        $sql = 'SELECT * FROM '.FDB::table('wogu_order').' WHERE artid='.$artid.' AND flag<2 AND isstop=0 AND userid='.$_FANWE['uid'];
        $orderinfo = FDB::fetchFirst($sql);
        if($orderinfo) {
            fHeader("location: /article.php?action=buy&orderid={$orderinfo['id']}");
            exit;
        }

        $share_detail = FS('Article')->getShareDetail($artid);
        if(!$share_detail || !$share_detail['anli']) {
            fHeader('location: /missing.html');
            exit;
        }

        if($_FANWE['uid'] == $share_detail['uid'])
            showError('错误信息', '不能购买自己的案例！', $_SERVER['HTTP_REFERER']);

        $cate = $_FANWE['cache']['goods_category']['all'][$share_detail['cate_id']];
        $paymulit = $cate['pay_mulit'];
        $paystep = 0;

        if($paymulit == 0)
            showError('错误信息', '此案例不支持分批支付！', $_SERVER['HTTP_REFERER']);

        // 创建进度执行表
        $config = include FANWE_ROOT . 'public/plan.php';
        $tip = htmlspecialchars(trim($_POST['tip']));
        if(empty($tip))
            showError('错误信息', '进度执行表名称不能为空！', $_SERVER['HTTP_REFERER']);

        if(empty($_POST['dateline']))
            showError('错误信息', '时间不能为空！', $_SERVER['HTTP_REFERER']);

        $dateline = strtotime($_POST['dateline']);
        $list_id = FDB::insert('wogu_plan_list', array(
            'uid' => $_FANWE['uid'],
            'dateline' => $dateline,
            'tip' => $tip,
            'ampm' => intval($_POST['ampm'])
        ), true);

        $pid = -1;
        $myid = 1;
        $item = $config[$myid];
        $data[0] = array(
            'dateline' => time(),
            'tipid' => -1,
            'tip' => ''
        );
        $itemid = FDB::insert('wogu_plan_items', array(
            'list_id' => $list_id,
            'pid' => $pid,
            'myid' => $myid,
            'dateline' => $dateline,
            'uid' => $_FANWE['uid'],
            'type' => $item['type'],
            'data' => serialize($data)
        ), true);
        // end_创建进度执行表

        $total_fee = $share_detail['price2'] > 0 ? $share_detail['price2'] : $share_detail['price'];
        $orderid = date('Ymdhis');
        $ordername = '火锅阁案例《'.$share_detail['title'].'》';
        $oid = FDB::insert('wogu_order', array(
            'paytype' => $paytype,
            'orderid' => $orderid,
            'ordername' => $ordername,
            'userid' => $_FANWE['uid'],
            'artid' => $artid,
            'shopid' => $share_detail['uid'],
            'total_fee' => $total_fee,
            'dateline' => time(),
            'pay_mulit' => $paymulit,
            'paystep' => $paystep,
            'plan_itemid' => $itemid
        ), true);

        FDB::update('wogu_plan_items', array('shopid' => $share_detail['uid'], 'orderid' => $oid, 'paystep' => $paystep), array('id' => $itemid));

        fHeader("location: /article.php?action=buy&orderid={$oid}");
        exit;
    }

    public function buyinit() {
        global $_FANWE;

        @session_start();
        $_SESSION['loc'] = $_GET['loc'] == 'art' ? 'art' : 'list';

        $paytype = intval($_GET['paytype']);
        $artid = intval($_GET['id']);
        $share_detail = FS('Article')->getShareDetail($artid);
        if(!$share_detail || !$share_detail['anli']) {
            fHeader('location: /missing.html');
            exit;
        }

        if($_FANWE['uid'] == $share_detail['uid'])
            showError('错误信息', '不能购买自己的案例！', $_SERVER['HTTP_REFERER']);

        $cate = $_FANWE['cache']['goods_category']['all'][$share_detail['cate_id']];
        $paymulit = $cate['pay_mulit'];
        $paystep = 0;

        $sql = 'SELECT * FROM '.FDB::table('wogu_order').' WHERE artid='.$artid.' AND flag<2 AND isstop=0 AND userid='.$_FANWE['uid'];
        $orderinfo = FDB::fetchFirst($sql);
        if(!$orderinfo) {
            // 如果分期付款的，显示创建进度执行表窗口，否则创建订单直接付款
            if($paymulit) {
                fHeader("location: /article.php?action=show&op=plan&id={$artid}&paytype={$paytype}");
                exit;
            } else {
                $total_fee = $share_detail['price2'] > 0 ? $share_detail['price2'] : $share_detail['price'];
                $orderid = date('Ymdhis');
                $ordername = '火锅阁案例《'.$share_detail['title'].'》';
                $oid = FDB::insert('wogu_order', array(
                    'paytype' => $paytype,
                    'orderid' => $orderid,
                    'ordername' => $ordername,
                    'userid' => $_FANWE['uid'],
                    'artid' => $artid,
                    'shopid' => $share_detail['uid'],
                    'total_fee' => $total_fee,
                    'dateline' => time(),
                    'pay_mulit' => $paymulit,
                    'paystep' => $paystep,
                    'red_money' => $share_detail['red_money']
                ), true);
                fHeader("location: /article.php?action=buy&orderid={$oid}");
                exit;
            }
        } else {
            fHeader("location: /article.php?action=buy&orderid={$orderinfo['id']}&paytype={$paytype}");
            exit;
        }
    }

    public function pingka() {
        global $_FANWE;

        if(!$_FANWE['uid'])
            showError('错误信息', '请先登陆！', FU('user/login'));

        $id = intval($_FANWE['request']['orderid']);
        if(!$id)
            showError('错误信息', '参数错误！', $_SERVER['HTTP_REFERER']);

        $sql = 'SELECT * FROM '.FDB::table('wogu_order').' WHERE id='.$id;
        $orderinfo = FDB::fetchFirst($sql);
        if(!$orderinfo) {
            showError('错误信息', '订单不存在！', $_SERVER['HTTP_REFERER']);
        }

        $orderid = $orderinfo['orderid'];
        $ordername = $orderinfo['ordername'];
        $total_fee = $orderinfo['total_fee'];
        $paytype = $orderinfo['paytype'];
        $paymulit = $orderinfo['pay_mulit'];
        $paystep = $orderinfo['paystep'];

        if(($paymulit && $paystep == 3) || (!$paymulit && $orderinfo['flag'] >= 1))
            showError('错误信息', '交易已完成！', '/shareinfo.php?action=order');

        if($paymulit) {
            $pers = array(0.3, 0.5, 0.2);
            $names = array('首付款', '中期款', '尾款');
            $thispay = $total_fee * $pers[$paystep];
            $orderid = str_repeat($paystep, 4) . $orderid;
            $ordername .= $names[$paystep];
        } else {
            $thispay = $total_fee;
        }

        $rmb = $_FANWE['user']['rmb_yu'] - $thispay;
        if($rmb < 0) {
            showError('错误信息', '余额不足！', $_SERVER['HTTP_REFERER']);
        }

        if($paymulit) {
            $paystep++;
            $flag = $paystep == 3 ? 2 : $orderinfo['flag'];
        } else {
            $flag = 2;
            $paystep = 0;
        }

        $sql = 'UPDATE '.FDB::table('wogu_order')." SET paystep={$paystep},flag={$flag} WHERE id='{$id}'";
        FDB::query($sql);

        $sql = 'UPDATE '.FDB::table('user')." SET rmb_yu={$rmb} WHERE uid='{$_FANWE['uid']}'";
        FDB::query($sql);
        if($paymulit) {
            //require FANWE_ROOT.'core/function/wogu.func.php';
            //dopay($orderinfo, $paystep, true);
            $sql = 'UPDATE '.FDB::table('wogu_plan_items')." SET paystep={$paystep} WHERE id='{$orderinfo['plan_itemid']}'";
            FDB::query($sql);
        }

        if(($paymulit&&$paystep==3) || !$paymulit)
            showSuccess('提示信息', '购买成功！', '/shareinfo.php?action=order');
        else {
            @session_start();
            if($_SESSION['loc'] == 'art')
                fHeader("location: /article.php?action=show&op=showpingka&id={$orderinfo['artid']}&orderid={$id}");
            else {
                fHeader("location: /list.php?action=plan&op=showitem&itemid={$orderinfo['plan_itemid']}");
            }
            exit;
        }
    }

    public function alipayapp() {
        global $_FANWE;

        if(empty($_FANWE['uid'])) {
            exit(json_encode(array(
                'status' => 1,
                'msg' => '请先登陆'
            )));
        }

        $artid = intval($_GET['id']);
        $share_detail = FS('Article')->getShareDetail($artid);
        if(!$share_detail || !$share_detail['anli']) {
            exit(json_encode(array(
                'status' => 1,
                'msg' => '案例不存在'
            )));
        }

        if($_FANWE['uid'] == $share_detail['uid']) {
            exit(json_encode(array(
                'status' => 1,
                'msg' => '不能购买自己的案例！'
            )));
        }

        $sql = 'DELETE FROM '.FDB::table('wogu_order').' WHERE artid='.$artid.' AND flag<2 AND isstop=0 AND userid='.$_FANWE['uid'];
        FDB::query($sql);

        $total_fee = $share_detail['price2'] > 0 ? $share_detail['price2'] : $share_detail['price'];
        $orderid = date('Ymdhis') . rand(0, 9);
        $ordername = '火锅阁案例《'.$share_detail['title'].'》';
        $newid = FDB::insert('wogu_order', array(
            'paytype' => 3,
            'orderid' => $orderid,
            'ordername' => $ordername,
            'userid' => $_FANWE['uid'],
            'artid' => $artid,
            'shopid' => $share_detail['uid'],
            'total_fee' => $total_fee,
            'dateline' => time(),
            'pay_mulit' => 0,
            'prepay_rate' => $share_detail['prepay_rate'],
            'paystep' => 0,
            'red_money' => $share_detail['red_money']
        ), true);

        if(!$newid) {
            exit(json_encode(array(
                'status' => 1,
                'msg' => '订单创建失败'
            )));
        }

        exit(json_encode(array(
            'status' => 0,
            'orderid' => $orderid
        )));
    }

    // public function alipayapp() {
    //     global $_FANWE;

    //     $artid = intval($_GET['id']);
    //     $share_detail = FS('Article')->getShareDetail($artid);
    //     if(!$share_detail || !$share_detail['anli']) {
    //         exit(json_encode(array(
    //             'status' => 1,
    //             'msg' => '案例不存在'
    //         )));
    //     }

    //     if($_FANWE['uid'] == $share_detail['uid']) {
    //         exit(json_encode(array(
    //             'status' => 1,
    //             'msg' => '不能购买自己的案例！'
    //         )));
    //     }

    //     $sql = 'DELETE FROM '.FDB::table('wogu_order').' WHERE artid='.$artid.' AND flag<2 AND isstop=0 AND userid='.$_FANWE['uid'];
    //     FDB::query($sql);

    //     $total_fee = $share_detail['price2'] > 0 ? $share_detail['price2'] : $share_detail['price'];
    //     $orderid = date('Ymdhis');
    //     $ordername = '火锅阁案例《'.$share_detail['title'].'》';
    //     $newid = FDB::insert('wogu_order', array(
    //         'paytype' => 3,
    //         'orderid' => $orderid,
    //         'ordername' => $ordername,
    //         'userid' => $_FANWE['uid'],
    //         'artid' => $artid,
    //         'shopid' => $share_detail['uid'],
    //         'total_fee' => $total_fee,
    //         'dateline' => time(),
    //         'pay_mulit' => 0,
    //         'paystep' => 0,
    //         'red_money' => $share_detail['red_money']
    //     ), true);

    //     if(!$newid) {
    //         exit(json_encode(array(
    //             'status' => 1,
    //             'msg' => '订单创建失败'
    //         )));
    //     }

    //     require_once(FANWE_ROOT . 'payment/app/alipay/common.inc.php');
    //     $aop = new AopClient;
    //     $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
    //     $aop->appId = APPID;
    //     $aop->rsaPrivateKey = RSA2_PRIVATE;
    //     $aop->format = "json";
    //     $aop->charset = "UTF-8";
    //     $aop->signType = "RSA2";
    //     $aop->alipayrsaPublicKey = RSA2_PUPLIC;
    //     //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
    //     $request = new AlipayTradeAppPayRequest();
    //     //SDK已经封装掉了公共参数，这里只需要传入业务参数
    //     $bizcontent = "{\"body\":\"".$ordername."\","
    //                     . "\"subject\": \"".$ordername."\","
    //                     . "\"out_trade_no\": \"".$orderid."\","
    //                     . "\"timeout_express\": \"30m\","
    //                     . "\"total_amount\": \"".$total_fee."\","
    //                     . "\"product_code\":\"QUICK_MSECURITY_PAY\""
    //                     . "}";
    //     $request->setNotifyUrl(NOTIFY_URL);
    //     $request->setBizContent($bizcontent);
    //     $response = $aop->sdkExecute($request);


    //     exit(json_encode(array(
    //         'status' => 0,
    //         'orderInfo' => $response,
    //         'orderid' => $orderid
    //     )));
    // }

    public function buy() {
        global $_FANWE;

        if(!$_FANWE['uid'])
            showError('错误信息', '请先登陆！', FU('user/login'));

        $id = intval($_GET['orderid']);
        if(!$id)
            showError('错误信息', '参数错误！');

        $sql = 'SELECT * FROM '.FDB::table('wogu_order').' WHERE id='.$id;
        $orderinfo = FDB::fetchFirst($sql);
        if(!$orderinfo) {
            showError('错误信息', '订单不存在！');
        }

        $orderid = $orderinfo['orderid'];
        $ordername = $orderinfo['ordername'];
        $total_fee = $orderinfo['total_fee'];
        $paytype = isset($_GET['paytype']) ? intval($_GET['paytype']) : $orderinfo['paytype'];
        $paymulit = $orderinfo['pay_mulit'];
        $paystep = $orderinfo['paystep'];

        if(($paymulit && $paystep == 3) || (!$paymulit && $orderinfo['flag'] >= 1))
            showError('错误信息', '交易已完成！', '/shareinfo.php?action=order');

        if($paymulit) {
            $pers = array(0.3, 0.5, 0.2);
            $names = array('首付款', '中期款', '尾款');
            $thispay = $total_fee * $pers[$paystep];
            $orderid = str_repeat($paystep, 4) . $orderid;
            $ordername .= $names[$paystep];
        } else {
            $thispay = $total_fee;
        }

        if($paytype == 0) {
            require_once(FANWE_ROOT . 'payment/alipay.php');
            $aliapy_config = include(FANWE_ROOT . 'payment/alipay_config.php');

            //构造要请求的参数数组
            $parameter = array(
                'service'            => 'create_direct_pay_by_user',
                'payment_type'        => '1',
                'partner'            => $aliapy_config['partner'],
                '_input_charset'    => $aliapy_config['input_charset'],
                'seller_email'        => $aliapy_config['seller_email'],
                'return_url'        => $aliapy_config['return_url'],
                'notify_url'        => $aliapy_config['notify_url'],
                'out_trade_no'        => $orderid,
                'subject'            => $ordername,
                'body'                => $ordername,
                'total_fee'            => $thispay
            );

            //构造即时到帐接口
            $alipayService = new AlipayService($aliapy_config);
            $html_text = $alipayService->create_direct_pay_by_user($parameter);
            include template('page/article/article_dopayment');
            display();
        } elseif($paytype == 1) {
            include_once FANWE_ROOT . 'payment/unionpay/func/common.php';
            include_once FANWE_ROOT . 'payment/unionpay/func/SDKConfig.php';
            include_once FANWE_ROOT . 'payment/unionpay/func/secureUtil.php';
            include_once FANWE_ROOT . 'payment/unionpay/func/log.class.php';

            // 初始化日志
            $log = new PhpLog ( SDK_LOG_FILE_PATH, "PRC", SDK_LOG_LEVEL );
            $log->LogInfo ( "============处理前台请求开始===============" );
            // 初始化日志
            $params = array(
                'version' => '5.0.0',				//版本号
                'encoding' => 'utf-8',				//编码方式
                'certId' => getSignCertId (),			//证书ID
                'txnType' => '01',				//交易类型
                'txnSubType' => '01',				//交易子类
                'bizType' => '000201',				//业务类型
                'frontUrl' =>  SDK_FRONT_NOTIFY_URL,  		//前台通知地址
                'backUrl' => SDK_BACK_NOTIFY_URL,		//后台通知地址
                'signMethod' => '01',		//签名方法
                'channelType' => '08',		//渠道类型，07-PC，08-手机
                'accessType' => '0',		//接入类型
                'merId' => '898420148160352',		        //商户代码，请改自己的测试商户号
                'orderId' => $orderid,	//商户订单号
                'txnTime' => date('YmdHis'),	//订单发送时间
                'txnAmt' => $thispay*100,		//交易金额，单位分
                'currencyCode' => '156',	//交易币种
                'defaultPayType' => '0001',	//默认支付方式
                //'orderDesc' => '订单描述',  //订单描述，网关支付和wap支付暂时不起作用
                'reqReserved' =>' 透传信息', //请求方保留域，透传字段，查询、通知、对账文件中均会原样出现
            );
            // 签名
            sign ( $params );

            // 前台请求地址
            $front_uri = SDK_FRONT_TRANS_URL;
            $log->LogInfo ( "前台请求地址为>" . $front_uri );
            // 构造 自动提交的表单
            $html_form = create_html ( $params, $front_uri );

            $log->LogInfo ( "-------前台交易自动提交表单>--begin----" );
            $log->LogInfo ( $html_form );
            $log->LogInfo ( "-------前台交易自动提交表单>--end-------" );
            $log->LogInfo ( "============处理前台请求 结束===========" );
            echo $html_form;
        } elseif($paytype == 2) {
            @session_start();
            if($_SESSION['loc'] == 'art')
                fHeader("location: /article.php?action=show&op=showpingka&id={$orderinfo['artid']}&orderid={$id}");
            else {
                fHeader("location: /list.php?action=plan&op=showitem&subop=showpingka&itemid={$orderinfo['plan_itemid']}");
            }
            exit;
        }
        exit;
    }

    public function zan() {
        global $_FANWE;

        if($_FANWE['user']['user_type'] == 1 && $_FANWE['user']['realname_shop'] == 0)
            exit('2');

        $id = intval($_GET['id']);
        if($id) {
            $sql = 'UPDATE '.FDB::table('article').' SET zai_num=zai_num+1 WHERE id='.$id;
            FDB::query($sql);
            // 如果是用户，看有无消费记录
            $addon = '';
            if($_FANWE['user']['user_type'] == 0) {
                $sql = 'SELECT COUNT(*) AS num FROM '.FDB::table('wogu_order').' WHERE userid='.$_FANWE['uid'].' AND flag>=1';
                $r = FDB::fetchFirst($sql);
                if($r['num'] > 0) {
                    $addon .= ',jy_num=jy_num+1';
                }
            } else {
                $addon .= ',jy_num=jy_num+1';
            }
            $sql = 'UPDATE '.FDB::table('user').' SET zan_num=zan_num+1'.$addon.' WHERE uid='.$_FANWE['uid'];
            FDB::query($sql);
            exit('1');
        }

        exit('0');
    }
}
?>